﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Linq;
using System.Collections.Generic;

namespace DiscoveryLogic.UI.Layouts
{
    public static class Utils
    {
        public static Color HexToColor(string hex)
        {
            string a = hex.Substring(1, 2);
            string r = hex.Substring(3, 2);
            string g = hex.Substring(5, 2);
            string b = hex.Substring(7, 2);

            Color c = new Color();
            c.A = Convert.ToByte(a, 16);
            c.R = Convert.ToByte(r, 16);
            c.G = Convert.ToByte(g, 16);
            c.B = Convert.ToByte(b, 16);

            return c;
        }

        //make all the dates 1 to 3 months apart
        public static DateTime MoveDateWithinRange(IEnumerable<DateTime> originalRange, DateTime dateTime, DateTime startDate, DateTime endDate)
        {
            DateTime min = originalRange.Min();
            DateTime max = originalRange.Max();

            long bot =  (max - min).Ticks;
            double percentage = bot <= 0? 0 : (((double)(dateTime - min).Ticks) / bot);

            TimeSpan span = endDate - startDate;

            DateTime newDate = startDate.AddTicks(Convert.ToInt64(span.Ticks * percentage));

            return newDate;
        }

        public static DateTime MakeDate(DateTime dateTime, int dayOffset, int monthOffset)
        {
            return MakeDateDayOffset(MakeDateMonthOffset(dateTime, monthOffset), dayOffset);
        }

        public static DateTime MakeDateDayOffset(DateTime dateTime, int dayOffset)
        {
            if (dateTime.Year >= 9999) return dateTime;

            DateTime now = DateTime.Today.Add(TimeSpan.FromDays(dayOffset));
            return new DateTime(
                now.Year, now.Month, now.Day, dateTime.Hour, dateTime.Minute, dateTime.Second);
        }
        

        public static DateTime MakeDateMonthOffset(DateTime dateTime, int monthOffset)
        {
            if (dateTime.Year >= 9999) return dateTime;

            DateTime now = DateTime.Now.AddMonths(monthOffset);
            return new DateTime(
                now.Year, now.Month, ToDay(now, dateTime.Day), dateTime.Hour, dateTime.Minute, dateTime.Second);
        }

        private static int ToDay(DateTime now, int day)
        {
            //make sure we keep the current day or at most the last day of the month
            return Math.Min(day, DateTime.DaysInMonth(now.Year, now.Month));
        }

    }
}
